/**
 * @file app
 */
import express from 'express';
import { Lifetime, asClass } from 'awilix';
import { loadControllers, scopePerRequest } from 'awilix-express';
import container from './container';
import bodyParser from 'body-parser';
import path from 'path';
import fs from 'fs';
import { baseMiddleware } from './middleware/base';
import initialize from './initialize';
import cookieParser from 'cookie-parser';

import axios from 'axios';
import { post } from './http';
import schedule from "node-schedule";

const app = express();
app.use(express.static(path.resolve(__dirname, '../client')));
app.use(cookieParser());
app.use(bodyParser());
app.use(scopePerRequest(container));
app.use(baseMiddleware(app));
app.use('/api', loadControllers('api/*.js', {
  cwd: __dirname,
  lifetime: Lifetime.SINGLETON
}));

export default async function run() {
  await initialize(app);

  // 依赖注入配置service层和dao层
  container.loadModules(['services/*Service.js', 'daos/*Dao.js'], {
    formatName: 'camelCase',
    register: asClass,
    cwd: path.resolve(__dirname)
  });

  app.get('*', (req, res) => {
    const html = fs.readFileSync(path.resolve(__dirname, '../client', 'index.html'), 'utf-8');
    res.send(html);
  });

  app.listen(9001, err => {
    if (err) {
      console.error(err);
      return;
    }
    console.log('Listening at http://localhost:9001');
  });


  const httpGet = () => {
    const api = 'http://127.0.0.1:9001/api/ipl/bulkIpls';
    const ipl = 'http://http.tiqu.alicdns.com/getip3?num=300&type=2&pro=&city=0&yys=100017&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=';
    axios({
      method: 'get',
      url: ipl,
    }).then(res => {
      console.log(res.data.data);
      let list = res.data.data;
      let ipl = [];
      list.map(item => {
        ipl.push({
          t_ipl: item.ip + ':' + item.port
        })
      })
      let params = { ipls: ipl }
      post(api, params).then(res => {
        console.log(res.success)
      }).catch(err => {
        console.log(err);
      })
    }).catch(err => {
      console.log(err);
    });
  }

  let rule = new schedule.RecurrenceRule();
  let times = [1,6,11,16,21,26,31,36,41,46,51,56];
  // 5分钟请求一次
  rule.minute  = times;
  // 5秒钟请求一次
  // rule.second = times;
  schedule.scheduleJob(rule, () => {
    httpGet();
  });
}